#!/bin/bash
# OpenMPTCProuter VPS端一键安装脚本（优化版）
echo "版本：test03"

# 配置参数
SUPPORTED_KERNELS=("5.4" "6.1" "6.6")
OFFICIAL_SCRIPT="https://www.openmptcprouter.com/server/debian-x86_64.sh"
DOWNLOAD_PROXY=""
DEFAULT_KERNEL="5.4"
CF_WORKER_MIRROR=""  # 替换为您的 Workers 地址用来替换repo.openmptcprouter.com加速下载

# 颜色定义
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
RESET='\033[0m'
BLUE='\033[34m'

# 国内镜像源列表（用于 bullseye）
MIRRORS=(
  "https://mirrors.163.com/debian"
  "https://mirrors.ustc.edu.cn/debian"
  "https://repo.huaweicloud.com/debian"
  "https://mirrors.tencent.com/debian"
  "https://mirrors.aliyun.com/debian"
)

# 国内存档源列表（用于 buster-backports）
ARCHIVE_MIRRORS=(
  "https://mirrors.163.com/debian-archive/debian"
  "https://mirrors.aliyun.com/debian-archive/debian"
  "https://repo.huaweicloud.com/debian-archive/debian"
)

# 检查并安装curl
install_curl() {
  if ! command -v curl &> /dev/null; then
    echo -e "${YELLOW}安装 curl...${RESET}"
    apt-get update && apt-get install -y curl
  fi
}

# 自动安装依赖
check_and_install_deps() {
  echo -e "${YELLOW}检查并安装必要的依赖...${RESET}"
  local packages=("wget" "gnupg2" "jq" "lsb-release")
  for pkg in "${packages[@]}"; do
    if ! dpkg-query -W -f='${Status}' "$pkg" 2>/dev/null | grep -q "ok installed"; then
      echo -e "${YELLOW}安装 $pkg...${RESET}"
      apt update && apt install -y "$pkg"
      if ! dpkg-query -W -f='${Status}' "$pkg" 2>/dev/null | grep -q "ok installed"; then
        echo -e "${RED}$pkg 安装失败，请检查网络或源配置！${RESET}"
        exit 1
      fi
    fi
  done
}


# 检查和配置 CF Worker 反代
check_cf_worker() {
  if [ -z "$CF_WORKER_MIRROR" ]; then
    echo -e "${YELLOW}未检测到 repo.openmptcprouter 的 Worker 反代地址${RESET}"
    echo -e "${GREEN}1) 是，使用 CF 反代（默认）${RESET}"
    echo -e "${GREEN}2) 否，使用原始地址${RESET}"
    read -p "请输入选项 (1/2): " -n 1 -r cf_choice < /dev/tty
    echo ""
    case "$cf_choice" in
      1|"")
        read -p "请输入反代地址 (如 omr.example.com): " custom_cf < /dev/tty
        CF_WORKER_MIRROR="${custom_cf#https://}"
        echo -e "${GREEN}已设置为: $CF_WORKER_MIRROR${RESET}"
        ;;
      2)
        CF_WORKER_MIRROR="repo.openmptcprouter.com"
        echo -e "${GREEN}将使用原始地址: $CF_WORKER_MIRROR${RESET}"
        ;;
      *)
        echo -e "${RED}无效选择，请输入 1 或 2${RESET}"
        check_cf_worker ;;
    esac
  fi
}

# 选择apt-get源
choose_mirror() {
  if [[ "$(lsb_release -cs)" == "bookworm" ]]; then
    echo -e "${YELLOW}是否更换apt-get源？${RESET}"
    echo -e "${GREEN}1) 163 源${RESET}"
    echo -e "${GREEN}2) 清华源${RESET}"
    echo -e "${GREEN}3) 阿里云源${RESET}"
    echo -e "${GREEN}0) 不更换（默认）${RESET}"
    read -p "请输入选项 (0/1/2/3): " -n 1 -r choice < /dev/tty
    echo ""
    case "$choice" in
      1)
        if command -v curl &> /dev/null; then
          echo -e "${YELLOW}正在更换为 163 源...${RESET}"
          curl -sSL "https://gitee.com/t88t/test/raw/master/debian12-163-sources.list" > /etc/apt-get/sources.list
          apt-get update
        else
          echo -e "${YELLOW}未检测到 curl，使用 wget 更换为 163 源...${RESET}"
          wget -qO- "https://gitee.com/t88t/test/raw/master/debian12-163-sources.list" > /etc/apt-get/sources.list
          apt-get update
        fi
        install_curl ;;
      2)
        if command -v curl &> /dev/null; then
          echo -e "${YELLOW}正在更换为清华源...${RESET}"
          curl -sSL "https://gitee.com/t88t/test/raw/master/debian12-tsinghua-sources.list" > /etc/apt-get/sources.list
          apt-get update
        else
          echo -e "${YELLOW}未检测到 curl，使用 wget 更换为清华源...${RESET}"
          wget -qO- "https://gitee.com/t88t/test/raw/master/debian12-tsinghua-sources.list" > /etc/apt-get/sources.list
          apt-get update
        fi
        install_curl ;;
      3)
        if command -v curl &> /dev/null; then
          echo -e "${YELLOW}正在更换为阿里云源...${RESET}"
          curl -sSL "https://gitee.com/t88t/test/raw/master/debian12-aliyun-sources.list" > /etc/apt-get/sources.list
          apt-get update
        else
          echo -e "${YELLOW}未检测到 curl，使用 wget 更换为阿里云源...${RESET}"
          wget -qO- "https://gitee.com/t88t/test/raw/master/debian12-aliyun-sources.list" > /etc/apt-get/sources.list
          apt-get update
        fi
        install_curl ;;
      0|"")
        echo -e "${GREEN}跳过更换apt-get源。${RESET}"
        install_curl ;;
      *)
        echo -e "${RED}无效输入，请重新选择！${RESET}"
        choose_mirror ;;
    esac
  fi
}

# 选择内核
choose_kernel() {
  echo -e "${GREEN}请选择要安装的内核版本:${RESET}"
  echo -e "${GREEN}1) 5.4（默认）${RESET}"
  echo -e "${GREEN}2) 6.1${RESET}"
  echo -e "${GREEN}3) 6.6${RESET}"
  read -p "请输入选项 (1/2/3): " -n 1 -r choice < /dev/tty
  echo ""
  case "$choice" in
    1|"") KERNEL="5.4" ;;
    2) KERNEL="6.1" ;;
    3) KERNEL="6.6" ;;
    *) echo -e "${RED}无效选择，请重新输入！${RESET}"; choose_kernel ;;
  esac
}

# 询问是否替换 OMR_VERSION（仅在选择 5.4 内核时）
ask_replace_omr_version() {
  if [ "$KERNEL" == "5.4" ]; then
    echo -e "${GREEN}是否将 OMR_VERSION 替换为 0.1030？${RESET}"
    echo -e "${GREEN}1) 是${RESET}"
    echo -e "${GREEN}2) 否（默认）${RESET}"
    read -p "请输入选项 (1/2): " -n 1 -r choice < /dev/tty
    echo ""
    case "$choice" in
      1) REPLACE_OMR_VERSION=true ;;
      2|"") REPLACE_OMR_VERSION=false ;;
      *) echo -e "${RED}无效选择，请重新输入！${RESET}"; ask_replace_omr_version ;;
    esac
  else
    REPLACE_OMR_VERSION=false
  fi
}

# 选择下载方式
choose_download_method() {
  echo -e "${GREEN}请选择安装程序下载方式（github）:${RESET}"
  echo -e "${GREEN}1) hosts替换github官方ip，默认${RESET}"
  echo -e "${GREEN}2) 使用默认加速（ghproxy.com）${RESET}"
  echo -e "${GREEN}3) 输入自定义加速链接${RESET}"
  read -p "请输入选项 (1/2/3): " -n 1 -r choice < /dev/tty
  echo ""
  case "$choice" in
    1|"") DOWNLOAD_PROXY="" ;;
    2) DOWNLOAD_PROXY="https://ghproxy.com/" ;;
    3)
      read -p "请输入自定义加速链接: " custom_proxy < /dev/tty
      DOWNLOAD_PROXY="$custom_proxy" ;;
    *) echo -e "${RED}无效选择，请重新输入！${RESET}"; choose_download_method ;;
  esac
}

# 更新 GitHub Hosts
update_github_ip() {
  echo -e "${YELLOW}正在更新 GitHub 的 IP 地址...${RESET}"
  GITHUB_IPS=$(curl -s https://api.github.com/meta | jq -r '.git[]')
  if [[ -z "$GITHUB_IPS" ]]; then
    echo -e "${RED}无法获取 GitHub 最新 IP，跳过更新 /etc/hosts${RESET}"
    return
  fi
  # 删除旧的 github 主机记录
  sed -i "/github.com/d" /etc/hosts
  for ip in $GITHUB_IPS; do
    echo "$ip github.com" >> /etc/hosts
    echo "$ip objects.githubusercontent.com" >> /etc/hosts
    echo "$ip raw.githubusercontent.com" >> /etc/hosts
  done
  echo -e "${GREEN}GitHub 的 IP 地址已更新！${RESET}"
}

# 测试源是否可用
test_source() {
  local url=$1
  local dist=$2
  echo -e "${YELLOW}测试 $url $dist 是否可用...${RESET}"
  if curl -s -I "$url/dists/$dist/Release" | grep -q "200 OK"; then
    echo -e "${GREEN}$url $dist 可用${RESET}"
    return 0
  else
    echo -e "${RED}$url $dist 不可用${RESET}"
    return 1
  fi
}

# 下载并优化官方安装脚本
download_script() {
  echo -e "${YELLOW}获取安装程序...${RESET}"
  local retries=3
  for ((i=1; i<=retries; i++)); do
    if curl -kL "${DOWNLOAD_PROXY}${OFFICIAL_SCRIPT}" -o /tmp/omr_install.sh; then
      rm -f /etc/apt-get/sources.list.d/bullseye.list
      rm -f /etc/apt-get/sources.list.d/buster-backports.list

      local bullseye_source="deb http://deb.debian.org/debian bullseye main"
      local buster_backports_source="deb http://archive.debian.org/debian buster-backports main"

      # 测试并替换 bullseye 源
      for mirror in "${MIRRORS[@]}"; do
        if test_source "$mirror" "bullseye"; then
          sed -i "s|$bullseye_source|deb $mirror bullseye main|g" /tmp/omr_install.sh
          bullseye_source="deb $mirror bullseye main"
          echo -e "${GREEN}使用 $mirror 替换 bullseye 源${RESET}"
          break
        fi
      done
      if [ "$bullseye_source" == "deb http://deb.debian.org/debian bullseye main" ]; then
        echo -e "${YELLOW}所有国内源 bullseye 不可用，保留 deb.debian.org${RESET}"
      fi

      # 测试并替换 buster-backports 源（优先使用国内存档源）
      local found_available=false
      for archive_mirror in "${ARCHIVE_MIRRORS[@]}"; do
        if test_source "$archive_mirror" "buster-backports"; then
          sed -i "s|$buster_backports_source|deb $archive_mirror buster-backports main|g" /tmp/omr_install.sh
          buster_backports_source="deb $archive_mirror buster-backports main"
          echo -e "${GREEN}使用 $archive_mirror 替换 buster-backports 源${RESET}"
          found_available=true
          break
        fi
      done

      # 如果所有国内存档源不可用，回退到 archive.debian.org
      if ! $found_available; then
        echo -e "${YELLOW}所有国内存档源 buster-backports 不可用，使用 archive.debian.org${RESET}"
        if test_source "http://archive.debian.org/debian" "buster-backports"; then
          echo -e "${GREEN}archive.debian.org buster-backports 可用${RESET}"
        else
          echo -e "${RED}archive.debian.org buster-backports 不可用，请检查网络${RESET}"
        fi
      fi

      # 替换官方脚本中的 repo.openmptcprouter.com 为 CF Workers 反代地址
      sed -i "s|repo.openmptcprouter.com|$CF_WORKER_MIRROR|g" /tmp/omr_install.sh
      echo -e "${GREEN}已将 repo.openmptcprouter.com 替换为 $CF_WORKER_MIRROR${RESET}"

      # 如果选择替换 OMR_VERSION
      if [ "$REPLACE_OMR_VERSION" == "true" ]; then
        sed -i 's|^OMR_VERSION=.*|OMR_VERSION="0.1030"|' /tmp/omr_install.sh
        echo -e "${GREEN}已将 OMR_VERSION 设置为 \"0.1030\"${RESET}"
      fi

      return 0
    fi
    sleep $((i*2))
  done
  echo -e "${RED}安装脚本下载失败${RESET}" && exit 1
}

# 新增函数：选择是否切换 pip 国内源
choose_pip_mirror() {
  echo -e "${YELLOW}是否切换 pip 国内源？${RESET}"
  echo -e "${GREEN}1) 切换 pip 国内源（例如清华镜像），（默认）${RESET}"
  echo -e "${GREEN}2) 保持原有设置${RESET}"
  read -p "请输入选项 (1/2): " -n 1 -r pip_choice < /dev/tty
  echo ""
  case "$pip_choice" in
    1|"")
      mkdir -p ~/.pip
      cat > ~/.pip/pip.conf <<EOF
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
EOF
      echo -e "${GREEN}pip 已切换为使用清华镜像${RESET}"
      ;;
    2)
      echo -e "${YELLOW}保持原有 pip 配置，不进行替换${RESET}"
      ;;
    *)
      echo -e "${RED}无效选择，请重新输入！${RESET}"
      choose_pip_mirror
      ;;
  esac
}


# 检查安装是否成功
check_installation() {
  if [ -f "/root/openmptcprouter_config.txt" ]; then
    echo -e "${GREEN}[成功] OpenMPTCPRouter 已安装！${RESET}"
  else
    echo -e "${RED}[失败] OpenMPTCPRouter 安装未完成，未找到 /root/openmptcprouter_config.txt${RESET}"
    exit 1
  fi
}

# 主执行流程
main() {
  [[ $EUID -eq 0 ]] || { echo -e "${RED}需要 root 权限${RESET}"; exit 1; }
  [[ -e /dev/net/tun ]] || { echo -e "${RED}TUN 设备未启用${RESET}"; exit 1; }
  choose_mirror  # 选择是否更换apt-get源并确保curl安装
  check_and_install_deps
  choose_kernel
  ask_replace_omr_version  # 询问是否替换 OMR_VERSION
  choose_download_method
  update_github_ip
  check_cf_worker
  download_script
  choose_pip_mirror    # 新增：选择是否切换 pip 国内源
  echo -e "${YELLOW}安装 OpenMPTCPRouter (内核:$KERNEL)...${RESET}"
  chmod +x /tmp/omr_install.sh
  export DEBIAN_FRONTEND=noninteractive KERNEL
  /tmp/omr_install.sh
  check_installation
}

# 入口点
if [ -t 0 ]; then
  echo -e "${YELLOW}提示：正在本地执行脚本。您也可以通过管道运行：curl -sSL URL | bash${RESET}"
fi

main "$@"